package com.mz.system.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mz.base.util.ATTSystem;

public class SessionFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		String uri = request.getRequestURI();
		//System.err.println("uri:"+uri);
		
		//Object sessionObj = request.getSession().getAttribute(ATTSystem.KEY_SESSION_LOGIN);
		Long userId = ATTSystem.MAP_SESSION_USERID.get(request.getSession().getId());
		if(userId==null){
			
			if(!isNotLoginUri(uri)){
				response.sendRedirect("/login.jsp");
				return;
			}
			
		}
		chain.doFilter(req, resp);
	}
	/**
	 * 判断该链接是否为需要登录后才可访问
	 * @param uri
	 * @return
	 */
	private boolean isNotLoginUri(String uri){
		String[] uriArray = ATTSystem.LIST_NOT_LOGIN_URI;
		
		boolean result = false;
		for(String str : uriArray){
			if(str.equals(uri)){
				result = true;
				break;
			}else{
				int index = str.indexOf("*");
				if(index == 0){
					str = str.substring(1);
					if(str.equals(uri.substring(uri.length()-str.length()))){
						result = true;
						break;
					}
				}else if(index>0){
					str = str.substring(0, str.indexOf("*"));
					if(uri.indexOf(str) == 0){
						result = true;
						break;
					}
				}
			}
		}
		
		return result;
	}

	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
	public void destroy() {
		
	}

}
